package kamikaze.service.product;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

import kamikaze.entity.Product;
import kamikaze.support.HttpMethod;
import kamikaze.support.Service;
import kamikaze.support.ServiceConfig;
import kamikaze.support.ServiceContext;
import kamikaze.support.ServiceException;

@ServiceConfig(path = "product/search", method = HttpMethod.GET)
public class SearchProductService implements Service {

	@SuppressWarnings("unchecked")
	@Override
	public String serve(ServiceContext ctx) throws Exception {

		ctx.getUserSession().ensureLoginAsUser();

		List<Product> productList = new ArrayList<Product>();
		List<Product> result = new ArrayList<Product>();

		boolean hasCriteria = false;

		// get all the input
		HttpServletRequest req = ctx.getRequest();
		String category = req.getParameter("prodCat");
		String name = req.getParameter("prodName");
		String prodPrice = req.getParameter("prodPrice");
		String prodPriceOperator = req.getParameter("prodPriceOperator");
		String prodRating = req.getParameter("prodRating");
		String prodCreatedDate = req.getParameter("prodCreatedDate");
		String sellerName = req.getParameter("sellerName");

		if ((category != null && !category.isEmpty())
				|| (name != null && !name.isEmpty())
				|| (prodPrice != null && !prodPrice.isEmpty())
				|| (prodPriceOperator != null && !prodPriceOperator.isEmpty())
				|| (prodRating != null && !prodRating.isEmpty())
				|| (prodCreatedDate != null && !prodCreatedDate.isEmpty())
				|| (sellerName != null && !sellerName.isEmpty())) {
			hasCriteria = true;
		}

		Query q = ctx.getEntityManager().createQuery(
				"Select p from Product p where deleted=false");
		productList = q.getResultList();
	

		if (hasCriteria) {

			if (category != null && !category.isEmpty()) {

				for (Product product:productList) {
					if (product.getCategory().toUpperCase().contains(category.toUpperCase()) ) {
						result.add(product);
					}
				}
				
				
			}

			if (name != null && !name.isEmpty()) {
				for (Product product:productList) {
					if (product.getName().toUpperCase().contains(name.toUpperCase()) && !result.contains(product)) {
						result.add(product);
					}
				}
			}

			if (prodPrice != null && !prodPrice.isEmpty()) {
				if (prodPriceOperator == null || prodPriceOperator.isEmpty()) {
					throw new ServiceException(
							"Please specify the operator for Product price");
				} else {
					prodPrice = prodPrice.replaceAll(",", "");

					BigDecimal price = BigDecimal.ZERO;
					Double dprice = Double.parseDouble(prodPrice);
					price = BigDecimal.valueOf(dprice);

					if ("eq".equalsIgnoreCase(prodPriceOperator)) {
						for (Product product:productList) {
							if (product.getPrice().compareTo(price) ==0 && !result.contains(product)) {
								result.add(product);
							}
						}
					} else if ("lt".equalsIgnoreCase(prodPriceOperator)) {
						for (Product product:productList) {
							if (product.getPrice().compareTo(price)<0 && !result.contains(product)) {
								result.add(product);
							}
						}
					} else if ("lte".equalsIgnoreCase(prodPriceOperator)) {
						for (Product product:productList) {
							if (product.getPrice().compareTo(price)<=0 && !result.contains(product)) {
								result.add(product);
							}
						}
					} else if ("gt".equalsIgnoreCase(prodPriceOperator)) {
						for (Product product:productList) {
							if (product.getPrice().compareTo(price)>0 && !result.contains(product)) {
								result.add(product);
							}
						}
					} else if ("gte".equalsIgnoreCase(prodPriceOperator)) {
						for (Product product:productList) {
							if (product.getPrice().compareTo(price)>=0 && !result.contains(product)) {
								result.add(product);
							}
						}
					} else {
						throw new ServiceException(
								"Please specify the operator for Product price");
					}
				}
			}

			if (prodRating != null && !prodRating.isEmpty()) {
				Integer rating = Integer.parseInt(prodRating);
				if (rating < 0 || rating > 5) {
					throw new ServiceException("Illegal Rating Value");
				}

				for (Product product:productList) {
					if (product.getRating()==rating && !result.contains(product)) {
						result.add(product);
					}
				}

			}

			if (prodCreatedDate != null && !prodCreatedDate.isEmpty()) {
				DateFormat formatter = new SimpleDateFormat(
						"dd-MM-yyyy");
				Date date = (Date) formatter.parse(prodCreatedDate);

				for (Product product:productList) {
					if (product.getCreatedDate().compareTo(date)==0 && !result.contains(product)) {
						result.add(product);
					}
				}
			}

			if (sellerName != null && !sellerName.isEmpty()) {
				for (Product product:productList) {
					if (product.getOwnerName().toUpperCase().contains(sellerName.toUpperCase()) && !result.contains(product)) {
						result.add(product);
					}
				}
			}


		}else {
			result = productList;
		}

		ctx.getRequest().setAttribute("products", result);
		return "product/search";

	}

}
